package main

import (
	"context"
	"errors"
	"fmt"
	"gitee.com/worklz/dtm-tcc-demo/common/log"
	"gitee.com/worklz/dtm-tcc-demo/common/util"
	_ "gitee.com/worklz/dtm-tcc-demo/gateway/pkg/boot"
	"gitee.com/worklz/dtm-tcc-demo/gateway/pkg/global"
	"gitee.com/worklz/dtm-tcc-demo/gateway/pkg/shutdown"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// go run main.go 19100
func main() {
	// 创建通道监听操作系统信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	// 启动http服务器
	server := &http.Server{
		Addr:    global.Config.App.Addr,
		Handler: global.GinEngine,
	}

	// 启动http服务器
	go func() {
		// 获取有效的本机IP
		localIP := util.GetValidLocalIP()
		// 解析实际监听的地址信息
		_, port, err := net.SplitHostPort(server.Addr)
		if err != nil {
			// 解析失败时直接输出完整地址
			fmt.Printf("http服务启动成功，监听地址: %s\r\n", server.Addr)
		} else {
			// 显示本机IP和监听端口
			fmt.Printf("http服务启动成功，监听地址: %s:%s\r\n", localIP, port)
		}

		if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			panic(fmt.Sprintf("启动http服务异常！%v", err))
		}
	}()

	// 等待关闭信号
	<-quit

	// 优雅关闭服务器
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer func() {
		cancel()
		log.Info("关闭服务成功")
	}()

	if err := server.Shutdown(ctx); err != nil {
		log.Error("关闭http服务异常！", err)
	}

	// 关闭处理
	shutdown.Handle()
}
